<template>
  <el-form :model="detailForm" :label-position="labelPosition" ref="detailForm" :class="isEdit?'':'formItem'">
    <el-card class="box-card" shadow="never">
      <div slot="header">
        <span>主车定损</span>
      </div>
      <el-row :gutter="20">
        <el-col :span="8">
          <el-form-item label="主车定损金额：" prop="vehicleAssessmentPrice"
                        :rules="isEdit ? rules.vehicleAssessmentPrice : []">
            <el-input v-if="isEdit" v-model="detailForm.vehicleAssessmentPrice" placeholder="输入主车定损金额"
                      v-thousand
                      @blur="handleBlur(detailForm.vehicleAssessmentPrice)"
                      @change="changeAmount('vehicleAssessmentPrice')"/>
            <span v-else>{{ format_thousand(detailForm.vehicleAssessmentPrice) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="人伤金额：" prop="persionAssessmentPrice">
            <el-input v-if="isEdit"
                      :disabled="detailForm.humanInjury == 2"
                      v-model="detailForm.persionAssessmentPrice" placeholder="输入人伤金额" v-thousand
                      @change="changeAmount('persionAssessmentPrice')"/>
            <span v-else>{{ format_thousand(detailForm.persionAssessmentPrice) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="其他：" prop="otherAssessmentPrice">
            <el-input v-if="isEdit" v-model="detailForm.otherAssessmentPrice" placeholder="输入其他金额" v-thousand
                      @change="changeAmount('otherAssessmentPrice')"/>
            <span v-else>{{ format_thousand(detailForm.otherAssessmentPrice) }}</span>
          </el-form-item>

        </el-col>

        <el-col :span="8">
          <el-form-item label="定损总计：" prop="assessmentTotalPrice">
            <el-input v-if="isEdit" v-thousand disabled v-model="detailForm.assessmentTotalPrice"/>
            <span v-else>{{ format_thousand(detailForm.assessmentTotalPrice) }}</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="签约维修厂/维修厂：" prop="maintenanceShopId"
                        :rules="isEdit && detailForm.assessmentTotalPrice >0 ? rules.maintenanceShopId : []">
            <el-select v-if="isEdit" v-model="detailForm.maintenanceShopId" @change="handleChange" style="width: 100%"
                       filterable placeholder="请选择签约维修厂维修厂">
              <el-option v-for="item in options" :key="item.supplierId" :label="item.supplierName"
                         :value="item.supplierId"/>
            </el-select>
            <span v-else>{{ detailForm.maintenanceShop }}</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="事故照片：" prop="accidentPhotos" :rules="isEdit ? rules.accidentPhotos : []">
            <ImageCommon v-model="detailForm.accidentPhotos" :limit="20" :disabled="!isEdit"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" :class="isEdit?'':'elRow'">
        <el-col :span="24">
          <el-form-item label="定损单：" prop="lossAssessmentOss" :rules="isEdit ? rules.lossAssessmentOss : []">
            <ImageCommon v-model="detailForm.lossAssessmentOss" :limit="20" :disabled="!isEdit" :upType="2"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>
  </el-form>
</template>

<script>
import {getDepreciationRule, getInsuranceSelectList, getList} from "@/api/cwgd/insuranceSelect";
import {toNumberAdd} from "@/utils/utils"
export default {
  name: "masterCarAssessment", //主车定损
  props: {
    value: {
      type: Object,
      default: {},
    },
    state: {
      type: String,
      default: "",
    },
  },
  computed: {
    detailForm: {
      get() {
        let that = this;
        const proxy = new Proxy(that.value, {
          get(target, key, value) {
            return Reflect.get(target, key);
          },
          set(target, key, value) {
            if (value) {
              that.handleClearValidate(key);
            }
            that.$emit("input", {...target, [key]: value});
            return true;
          },
        });
        return proxy;
      },
    },
    labelPosition() {
      if (this.isEdit) {
        return "top";
      } else {
        return "right";
      }
    },
    isEdit() {
      let bool;
      switch (this.state) {
        case "write":
          bool = true;
          break;
        case "disabled":
          bool = false;
          break;
        case "readonly":
          bool = false;
          break;
      }
      return bool;
    },
  },
  watch: {},
  data() {
    return {
      options: [],
      rules: {
        vehicleAssessmentPrice: [
          {required: true, message: "请输入主车定损金额", trigger: "blur"},
        ],
        maintenanceShopId: [
          {required: true, message: "请输入输入维修厂", trigger: "blur"},
        ],
        accidentPhotos: [
          {required: true, message: "请上传事故照片", trigger: "change"},
        ],
        lossAssessmentOss: [
          {required: true, message: "请上传定损单", trigger: "change"},
        ],
      },
      depreciationList:[]
    };
  },
  created() {
    this.handleList(4);
    this.handleDepreciationPlan()
  },
  mounted() {
  },
  methods: {
    handleList(val) {
      getInsuranceSelectList({businessTypeCode: val}).then((res) => {
        if (res.code === 200) {
          this.options = res.data;
        }
      });
    },

    handleDepreciationPlan() {
      getList().then(res => {
        if (res.code === 200) {
          this.depreciationList = res.data || []
        }
      })
    },

    handleChange(val) {
      this.value.maintenanceShopId = val;
      let supplierName = this.options
          .map((a) => {
            if (val === a.supplierId) {
              return a.supplierName;
            }
          })
          .filter((a) => a)[0];
      this.value.maintenanceShop = supplierName;
      this.detailForm.maintenanceShop = supplierName;
    },

    handleBlur(val) {
      if (val) {
        if(this.value.depreciationPlanId){
          let obj = this.depreciationList.filter(i => i.id === this.value.depreciationPlanId)[0]
          let num = (this.detailForm.vehicleAssessmentPrice - Number(obj.deductionAmount)) * Number(obj.scale) / 100
          this.value.depreciationPrice = this.detailForm.depreciationPrice = num > 0 ? num : 0
          console.log(num,"-=-=-=-=-=-=")
        }
      } else {
        this.value.depreciationPrice = this.detailForm.depreciationPrice = ''
        this.value.depreciationPlan = this.detailForm.depreciationPlan = ''
        this.value.depreciationPlanId = this.detailForm.depreciationPlanId = ''
      }
    },


    changeAmount(str) {
      let msg = /^(?:[1-9]\d*|0)(?:\.\d+)?$/;
      if (!msg.test(this.value[str])) {
        this.value[str] = "";
      } else {
        this.value[str] = this.value[str]
            .toString()
            .match(/^\d+(?:\.\d{0,2})?/)[0];
        this.sumPrice();
      }
      // if (str === 'vehicleAssessmentPrice') {
      //   return
      //   getDepreciationRule({vehicleAssessmentPrice: this.value[str]}).then(res => {
      //     if (res.code === 200) {
      //       this.$set(this.value, 'depreciationPlan', res.data?.depreciationPlan)
      //       this.$set(this.value, 'depreciationPrice', Number(res.data?.depreciationPrice) || 0)
      //     }
      //   })
      // }
    },

    sumPrice() {
      let num = 0;
      num = toNumberAdd(
          toNumberAdd(
              Number(this.detailForm.vehicleAssessmentPrice),
              Number(this.detailForm.persionAssessmentPrice)
          )
          ,
          Number(this.detailForm.otherAssessmentPrice))
      this.value.assessmentTotalPrice = num
          .toString()
          .match(/^\d+(?:\.\d{0,2})?/)[0];

      // let depreciationPrice = (this.value.assessmentTotalPrice - 5000) * 0.02;
      // let Price = depreciationPrice > 0 ? depreciationPrice : 0;
      // this.detailForm.depreciationPrice =
      //     Price.toString().match(/^\d+(?:\.\d{0,2})?/)[0];
    },

    handleEffect() {
      return new Promise((resolve, reject) => {
        this.$refs.detailForm.validate((valid) => {
          if (valid) {
            resolve();
          } else {
            this.locateToErr();
            reject();
          }
        });
      });
    },

    locateToErr() {
      this.$nextTick(() => {
        let isError = document.getElementsByClassName("is-error");
        isError[0].scrollIntoView({
          // 滚动到指定节点
          // 值有start,center,end，nearest，当前显示在视图区域中间
          block: "center",
          // 值有auto、instant,smooth，缓动动画（当前是慢速的）
          behavior: "smooth",
        });
      });
    },

    valid() {
      return new Promise((resolve) => {
        this.$refs.detailForm.validate((valid) => {
          resolve(valid);
        });
      });
    },

    //取消表单效验
    handleClearValidate(str) {
      this.$refs.detailForm.clearValidate(str);
    },
  },
};
</script>

<style lang="scss" scoped>
@import "@/styles/cwgd/formScss.scss";
</style>

